const express = require("express");
const multer = require("multer");
const router = express.Router();
const path = require("path");
const user = require("../model/user");

// 磁盘存储引擎
var storage = multer.diskStorage({
    // 存储的位置
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, "../public/photo"));
    },
    // 存储的文件名
    filename: function (req, file, cb) {
        let fileName =
            req.session.user._id + file.originalname.match(/\.[^\.]+$/g)[0];
        req.fileName = fileName;
        cb(null, fileName);
    }
});
let upload = multer({
    storage: storage, //代表存储到硬盘而不是内存
    fileFilter(req, file, cb) {
        //过滤器
        cb(null, /\.(jpg|jpeg|png|gif)$/.test(file.originalname)); //为false时不会保存
    }
    // ,limits : {
    //     fileSize : 1024*100 //限制文件大小100k
    // }
}).single("file");

// 上传头像路由
router.post("/photo", function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            res.send({
                code: 0,
                message: "图片上传失败，请稍后再试"
            });
        } else {
            user
                .updateOne({ _id: req.session.user._id }, { photo: req.fileName })
                .then(result => {
                    
                });
            res.send({
                code: 1,
                message: "头像上传成功，即将刷新页面"
            });
        }
    });
});

let fileName;
var articelstorage = multer.diskStorage({
    // 存储的位置
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, "../public/articelphoto"));
    },
    // 存储的文件名
    filename: function (req, file, cb) {
        fileName =
            parseInt(Math.random() * 10000) +
            "" +
            new Date().valueOf() +
            file.originalname.match(/\.[^\.]+$/g)[0];
        cb(null, fileName);
    }
});
let articelupload = multer({
    storage: articelstorage, //代表存储到硬盘而不是内存
    fileFilter(req, file, cb) {
        //过滤器
        cb(null, /\.(jpg|jpeg|png|gif)$/.test(file.originalname)); //为false时不会保存
    }
    // ,limits : {
    //     fileSize : 1024*100 //限制文件大小100k
    // }
}).single("file");

// 上传文章图片的路由
router.post("/artical_photo", function (req, res) {
    articelupload(req, res, function (err) {
        if (err) {
        } else {
            res.send({
                code: 0, //0表示成功，其它失败
                msg: "上传成功", //提示信息 //一般上传失败后返回
                data: {
                    src: `/articelphoto/${fileName}`
                }
            });
        }
    });
});

module.exports = router;
